package com.xiaoyang.lotterysystem.service.mq;

import cn.hutool.core.date.DateUtil;
import com.xiaoyang.lotterysystem.common.exception.ServiceException;
import com.xiaoyang.lotterysystem.common.utils.JacksonUtil;
import com.xiaoyang.lotterysystem.common.utils.MailUtil;
import com.xiaoyang.lotterysystem.common.utils.SMSUtil;
import com.xiaoyang.lotterysystem.controller.param.DrawPrizeParam;
import com.xiaoyang.lotterysystem.dao.dataobject.ActivityPrizeDO;
import com.xiaoyang.lotterysystem.dao.dataobject.WinningRecordDO;
import com.xiaoyang.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.xiaoyang.lotterysystem.dao.mapper.WinningRecordMapper;
import com.xiaoyang.lotterysystem.service.DrawPrizeService;
import com.xiaoyang.lotterysystem.service.activitystatus.ActivityStatusManager;
import com.xiaoyang.lotterysystem.service.dto.ConvertActivityStatusDTO;
import com.xiaoyang.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.xiaoyang.lotterysystem.service.enums.ActivityPrizeTiersEnum;
import com.xiaoyang.lotterysystem.service.enums.ActivityStatusEnum;
import com.xiaoyang.lotterysystem.service.enums.ActivityUserStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.xiaoyang.lotterysystem.common.config.DirectRabbitConfig.QUEUE_NAME;

@Slf4j
@Component
@RabbitListener(queues = QUEUE_NAME)
public class MqReceiver {

    @Autowired
    private DrawPrizeService drawPrizeService;
    @Autowired
    private ActivityStatusManager activityStatusManager;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private MailUtil mailUtil;
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Autowired
    private WinningRecordMapper winningRecordMapper;

    @RabbitHandler
    public void process(Map<String, String> message) {

        // 成功接收到消息
        log.info("MQ成功接收到消息,message:{}",
                JacksonUtil.writeValueAsString(message));
        String paramString = message.get("messageData");
        DrawPrizeParam param = JacksonUtil.readValue(paramString, DrawPrizeParam.class); // 反序列化

        // 处理抽奖流程
        try {
            // 校验抽奖请求是否有效
            if (!drawPrizeService.checkDrawPrizeParam(param)) {
                return;
            }

            // 状态扭转处理
            statusCovert(param);
            // 保存中奖者名单
            List<WinningRecordDO> winningRecordDOList = drawPrizeService.saveWinnerRecords(param);
            // 通知中奖者(短信 邮箱)
            // 处理中奖后续流程
            syncExecute(winningRecordDOList);

        } catch (ServiceException e) {
            log.error("处理 MQ 消息异常! {}:{}", e.getCode(), e.getMessage(), e);
            // 需要保证事务的一致性(回滚)
            rollback(param);
            // 抛出异常
            throw e;
        }catch (Exception e) {
            log.error("处理 MQ 消息异常!", e);
            // 需要保证事务的一致性(回滚)
            rollback(param);
            // 抛出异常
            throw e;
        }
    }

    /**
     * 处理抽象异常的回滚行为: 恢复处理请求之前的库表状态
     * @param param
     */
    private void rollback(DrawPrizeParam param) {
        // 1. 回滚状态:活动,奖品,人员
        // 状态是否需要回滚
        if (!statusNeedRollback(param)) {
            // 不需要回滚 return
            return;
        }
        // 需要回滚
        rollbackStatus(param);

        // 2. 回滚状态: 中奖者名单
        // 状态是否需要回滚
        if (!winnerNeedRollback(param)) {
            // 不需要回滚 return
            return;
        }
        // 需要回滚
        rollbackWinner(param);
    }

    /**
     * 回滚中奖记录: 删除奖品下的中奖者
     *
     * @param param
     */
    private void rollbackWinner(DrawPrizeParam param) {
        drawPrizeService.deleteRecords(param.getActivityId(), param.getPrizeId());
    }

    private boolean winnerNeedRollback(DrawPrizeParam param) {
        // 判断活动中的奖品是否存在中奖者
        int count = winningRecordMapper.countByAPId(param.getActivityId(), param.getPrizeId());
        return count > 0;
    }

    /**
     * 恢复相关状态
     *
     * @param param
     */
    private void rollbackStatus(DrawPrizeParam param) {
        ConvertActivityStatusDTO convertActivityStatusDTO = new ConvertActivityStatusDTO();
        convertActivityStatusDTO.setActivityId(param.getActivityId());
        convertActivityStatusDTO.setTargetActivityStatus(ActivityStatusEnum.RUNNING);
        convertActivityStatusDTO.setPrizeId(param.getPrizeId());
        convertActivityStatusDTO.setTargetPrizeStatus(ActivityPrizeStatusEnum.INIT);
        convertActivityStatusDTO.setUserIds(
                param.getWinnerList()
                        .stream()
                        .map(DrawPrizeParam.winner::getUserId)
                        .collect(Collectors.toList()));
        convertActivityStatusDTO.setTargetUserStatus(ActivityUserStatusEnum.INIT);
        activityStatusManager.rollbackHandlerEvent(convertActivityStatusDTO);
    }

    /**
     * 判断 活动,奖品,人员状态是否回滚
     * @param param
     * @return
     */
    private boolean statusNeedRollback(DrawPrizeParam param) {
        ActivityPrizeDO activityPrizeDO =
                activityPrizeMapper.selectAPId(param.getActivityId(), param.getPrizeId());

        if (activityPrizeDO.getStatus()
                .equalsIgnoreCase(ActivityPrizeStatusEnum.COMPLETED.name())) {
            return true;
        }
        return false;
    }

    /**
     * 并发处理抽象后续流程
     *
     * @param winningRecordDOList
     */
    private void syncExecute(List<WinningRecordDO> winningRecordDOList) {
        // 通过线程池 ThreadPoolTaskExecutor

        // 发送中奖者短信
        threadPoolTaskExecutor.execute(() -> sendMessage(winningRecordDOList));
        // 发送中奖者邮箱
        threadPoolTaskExecutor.execute(() -> sendMail(winningRecordDOList));

    }

    /**
     * 发送中奖者短信
     * @param winningRecordDOList
     */
    private void sendMessage(List<WinningRecordDO> winningRecordDOList) {
        if (CollectionUtils.isEmpty(winningRecordDOList)) {
            log.info("中奖者列表为空,不能发送短信!");
            return;
        }
        for (WinningRecordDO winningRecordDO : winningRecordDOList) {
            Map<String, String> map = new HashMap<>();
            map.put("name", winningRecordDO.getWinnerName());
            map.put("activityName", winningRecordDO.getActivityName());
            map.put("prizeTiers", ActivityPrizeTiersEnum.forName(winningRecordDO.getPrizeTier()).getMessage());
            map.put("prizeName", winningRecordDO.getPrizeName());
            map.put("winningTime", DateUtil.formatTime(winningRecordDO.getWinningTime()));

            smsUtil.sendMessage("SMS_473475053",
                    winningRecordDO.getWinnerPhoneNumber().getValue(),
                    JacksonUtil.writeValueAsString(map));
        }
    }

    /**
     * 发送中奖者邮箱
     * @param winningRecordDOList
     */
    private void sendMail(List<WinningRecordDO> winningRecordDOList) {
        if (CollectionUtils.isEmpty(winningRecordDOList)) {
            log.info("中奖者列表为空,不能发送邮件!");
            return;
        }
        for (WinningRecordDO winningRecordDO : winningRecordDOList) {
            String context = "Hi，" + winningRecordDO.getWinnerName() + "。恭喜你在"
                    + winningRecordDO.getActivityName() + "活动中获得"
                    + ActivityPrizeTiersEnum.forName(winningRecordDO.getPrizeTier()).getMessage()
                    + "：" + winningRecordDO.getPrizeName() + "。获奖时间为"
                    + DateUtil.formatTime(winningRecordDO.getWinningTime()) + "，请尽快领 取您的奖励！";

            mailUtil.sendSampleMail(winningRecordDO.getWinnerEmail(), "中奖通知", context);

        }
    }

    /**
     * 状态扭转
     *
     * @param param
     */
    private void statusCovert(DrawPrizeParam param) {
        ConvertActivityStatusDTO convertActivityStatusDTO = new ConvertActivityStatusDTO();
        convertActivityStatusDTO.setActivityId(param.getActivityId());
        convertActivityStatusDTO.setTargetActivityStatus(ActivityStatusEnum.COMPLETED);
        convertActivityStatusDTO.setPrizeId(param.getPrizeId());
        convertActivityStatusDTO.setTargetPrizeStatus(ActivityPrizeStatusEnum.COMPLETED);
        convertActivityStatusDTO.setUserIds(
                param.getWinnerList().stream()
                        .map(DrawPrizeParam.winner::getUserId)
                        .collect(Collectors.toList())
        );
        convertActivityStatusDTO.setTargetUserStatus(ActivityUserStatusEnum.COMPLETED);

        activityStatusManager.handlerEvent(convertActivityStatusDTO);
    }
}
